<!--
* description: 门店移库指令发起
* author: duanhy
* createdDate: 2020-11-11
-->
<template>
  <div>
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="false"
      :callback-obj="callbackObj"
    />
    <Batch-Add
      v-if="editBatchVisible"
      :is-dialog-visible="editBatchVisible"
      :dynamic-edit-row-data="editRowData"
      :popups-state="editPopupsState"
      :title-name="titleName"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import commApi from '@/api/ve'
import apiTransfer from '@/api/apiVeTransferManagement'
import OneTableTemplate from '@/components/templates/oneTable'
import BatchAdd from '../veTotalCommand/batchAdd'
import Vue from 'vue'
export default {
  name: 'StoreInstructions',
  components: {
    OneTableTemplate,
    BatchAdd
  },
  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'storeRelocation'], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '',
      dialogShow: false,
      editBatchVisible: false,
      selectionIndex: '',
      editRowData: {},
      selectionVal: [],
      // 网格查询API配置对象
      apiConfig: apiTransfer.listRelocationStore,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: '',
          size: 'small',
          clickEvent: () => this.batchAdd(),
          text: '新增',
          name: 'add',
          position: 'left',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          clickEvent: () => this.btn('vinSubmit', '1'),
          disabled: true,
          text: '提交',
          name: 'import',
          position: 'left',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.btn('vinScrap', '0'),
          disabled: true,
          text: '作废',
          name: '',
          position: 'left',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.queryTable(1),
          text: '查询',
          name: 'search',
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          clickEvent: () => this.reset(),
          text: '重置',
          name: 'reset',
          position: 'right'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '移库单：',
              codeField: 'movestockOrderCode',
              isMul: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '源仓库：',
              codeField: 'oldHouseId',
              textField: 'oldHouseName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'oldHouseId,oldHouseName',
              type: 'dropdownList',
              isMust: true,
              options: [
                { oldHouseId: '', oldHouseName: '' }
              ]
            },
            {
              compKey: 'compKey4',
              labelName: '目的库：',
              codeField: 'stockId',
              textField: 'stockName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              oFields: 'stockId,stockName',
              customObj: {
                api: apiTransfer.ListOfWarehouse,
                listQuery: {
                  warehouseId: '1'
                }
              }
            },
            {
              compKey: 'compKey5',
              labelName: '单据状态：',
              codeField: 'auditStatusId',
              textField: 'auditStatusName',
              component: () => import('@/components/org/LookupValue'),
              lookuptype: 'VE1079',
              type: 'dropdownList',
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '制单时间：',
              codeField: 'newDateStart,newDateEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              // dateOptionsType: '3', // 禁用当前日期之前的日期
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '申请时间：',
              codeField: 'applyTimeStart,applyTimeEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey8',
              labelName: '审核时间：',
              codeField: 'auditTimeStart,auditTimeEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '车系：',
              codeField: 'carSeriesId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'carSeriesId,carSeriesCn',
              customObj: {
                api: commApi.vehicleQuery
              }
            },
            {
              compKey: 'compKey10',
              labelName: '基础车型：',
              codeField: 'carConfigId',
              textField: 'carConfigCn',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'carConfigId,carConfigCn',
              parentFileds: 'value:carSeriesId',
              customObj: {
                api: commApi.ModelQuery,
                listQuery: {
                  carSeriesId: ''
                }
              }
            },
            {
              compKey: 'compKey11',
              labelName: '选装包：',
              codeField: 'optionalPagId',
              textField: 'optionalPagName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'optionalPagId,optionalPagName',
              parentFileds: 'value:carConfigId',
              customObj: {
                api: commApi.queryPackByModel,
                listQuery: {
                  carConfigId: ''
                }
              }
            },
            {
              compKey: 'compKey12',
              labelName: '车身颜色：',
              codeField: 'carColorId',
              textField: 'carColorName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carColorId,carColorName',
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: commApi.queryBodyColorByModel
              }
            },
            {
              compKey: 'compKey13',
              labelName: '内饰颜色：',
              codeField: 'carIncolorId',
              textField: 'carIncolorName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carIncolorId,carIncolorName',
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: commApi.queryInnerColorByModel
              }
            }
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'movestockOrderCode',
              label: '移库单',
              width: 120
            },
            {
              prop: 'oldHouseName',
              label: '源仓库'
            },
            {
              prop: 'stockName',
              label: '目的库'
            },
            {
              prop: 'auditStatusName',
              label: '单据状态'
            },
            {
              prop: 'auditOpinion',
              label: '审核意见'
            },
            {
              prop: 'vin',
              label: 'VIN'
            },
            {
              prop: 'carSeriesCn',
              label: '车系'
            },
            {
              prop: 'carConfigCn',
              label: '基础车型'
            },
            {
              prop: 'optionalPagName',
              label: '选装包'
            },
            {
              prop: 'carColorName',
              label: '车身颜色'
            },
            {
              prop: 'carIncolorName',
              label: '内饰颜色'
            },
            {
              prop: 'newDate',
              label: '制单时间'
            },
            {
              prop: 'applyMen',
              label: '申请人'
            },
            {
              prop: 'applyTime',
              label: '申请时间'
            },
            {
              prop: 'auditMen',
              label: '审核人'
            },
            {
              prop: 'auditTime',
              label: '审核时间'
            }
          ],
      formField: {
        md: '2',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: '',
        movestockOrderCode: '',
        vin: '',
        oldHouseId: '',
        oldHouseName: '',
        stockId: '',
        stockName: '',
        auditStatusId: '',
        auditStatusName: '',
        newDateStart: '',
        newDateEnd: '',
        applyTimeStart: '',
        applyTimeEnd: '',
        auditTimeStart: '',
        auditTimeEnd: ''
      },
      selectList: [],
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectList = selection
          this.handleSelectionChange(selection)
        }
      },
      // 是否使用刷新Key的方式刷新弹窗
      resetDialogKey: false,
      userNameShow: false
    }
  },

  created() {
    const that = this
    setTimeout(function() {
      that.queryTable(1)
    }, 0)
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs.multipleTable.list) {
        this.init()
      }
    })
  },
  methods: {
    // 原仓库查询
    init() {
      const newSelect = []
      this.$requestAPI(this.$getParams({
        apiConfig: apiTransfer.ListOfWarehouse,
        variables: {
          isEnable: '1',
          pageIndex: 1,
          pageSize: 500,
          warehouseId: '5'
          // dlrId: this.$refs.multipleTable.list[0].dlrId
          // dlrId: '42be223b451711eba2c00050569034e9'// 测试用
        }
      })).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        for (const k in response.rows) {
          newSelect.push({
            oldHouseId: response.rows[k].stockId,
            oldHouseName: response.rows[k].stockName
          })
        }
        for (const k in this.tableComponents) {
          if (this.tableComponents[k].codeField === 'oldHouseId') {
            this.tableComponents[k].options = newSelect
            return false
          }
        }
      }).catch(err => {
        console.info(err)
      })
    },
    // 提交&&作废importTransferSubmitStore&abolishTransferSubmitStore
    btn(type, num) {
      this.$refs['multipleTable'].listLoading = true
      var dataForm = {}
      console.log(num)
      dataForm[type] = num
      const obj = {
        uList: []
      }
      for (const k in this.selectList) {
        obj.uList.push({
          vin: this.selectList[k].vin,
          updateControlId: this.selectList[k].updateControlId
        })
      }
      Object.assign(dataForm, obj)
      this.$requestAPI(this.$getParams({
        apiConfig: apiTransfer.updateStoreTransferSubmit,
        variables: dataForm
      })).then(response => {
        this.$refs['multipleTable'].listLoading = false
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        this.$message({ message: response.msg, type: 'warn', uration: 2000 })
        this.queryTable(1)
      }).catch(err => {
        this.$refs['multipleTable'].listLoading = false
        console.info(err)
      })
    },
    // 设置表格选择框 是否禁用
    getSelectable(row, index) {
      if (row.auditStatusName === '待提交') {
        return true
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },
    close(type) {
      if (type === 1) {
        this.queryTable(1)
      }
      this.dialogShow = false
      this.editBatchVisible = false
    },
    batchAdd() {
      this.titleName = '门店移库指令新增'
      this.editRowData = { api: apiTransfer.listStockCarStore }
      this.editBatchVisible = true
    },
    // 保存传值过来
    save(formField) {
      if (formField.index !== '') {
        this.$refs['multipleTable'].list[formField.index] = formField
      } else {
        this.$refs['multipleTable'].list.push(formField)
      }
      // console.log(formField)
      // this.close()
    }
  }
}
</script>
